# -*- coding: utf-8 -*-
# File : mysql_util.py
# Author: taoyahui
# Date : 2021/3/23

import pymysql
import configparser
import os
root_dir = os.path.dirname(os.path.abspath('.'))
cf = configparser.ConfigParser()
cf.read("config.ini")

secs = cf.sections()
print(secs)
host = cf.get("Mysql-Database", "host")
port = cf.get("Mysql-Database", "port")
user = cf.get("Mysql-Database", "user")
password = cf.get("Mysql-Database", "password")
db = cf.get("Mysql-Database", "db")


def get_conn():
    conn = pymysql.connect(host=host, port=int(port), user=user, passwd=password,db=db, charset='utf8')
    return conn


def get_cursor(conn):
    return conn.cursor()


def exec_sql(conn, cursor, sql):
    try:
        cursor.execute(sql)
        result = cursor.fetchall()
        conn.commit()
        return result
    except BaseException as e:
        conn.rollback()
        print('Error: %s' % e)


def release(conn, cursor):
    if cursor:
        cursor.close()
    if conn:
        conn.close()


if __name__ == '__main__':
    conn = get_conn()
    cursor = get_cursor(conn)
    sql = f"select * from user"
    print(exec_sql(conn, cursor, sql)[0][0])
